<?php

/* 
 * controller 基类
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class BaseController {
    public $smarty = null;
    /**json返回数据,status, msg键值*/
    protected $ret = array(
        'status' => 999,
        'msg' => 'no msg',
    );
    /**主题名称即文件夹名称*/
    protected $theme_name = 'default';
    /**页面头说明*/
    protected $title = '默认页';
    /**日志类型*/
    protected $log_type = 'None';
    /**页码尺寸,默认10个*/
    protected $page_number = 10;
    /**Cookie Key*/
    protected $cookie_key = 'app_cookie'; 
    
    /**
     * 基础controller 
     */
    public function __construct() {
        $this->load_smarty();
        $host = $_SERVER['HTTP_HOST'];
        $this->assign('res_root', 'http://' . $host . '/Res/');        
        $this->setTemplate();
    }

    /**
     * 初使smarty
     */
    public function load_smarty() {
        $smarty = new x_smarty();
        $this->smarty = $smarty;        
    }
    /**
     * 设置主题目录
     */
    /**
     * 设置主题目录
     */
    protected function setTemplate($theme_name = 'default') {
        if($theme_name) {
            $this->theme_name = $theme_name;
        }
        $this->smarty->setTemplateDir(APP_PATH . 'views/' . $this->theme_name);
    }

    /**
     * 设置键与值
     * @param string $key 键
     * @param mix $value 值
     */
    public function assign($key, $value) {
        $this->smarty->assign($key, $value);
    } 
    /**
     * 渲染页面 
     * @param string $page_name 页面名称
     */
    public function display($page_name) {
        if(strpos($page_name, '.html') === false) {
            $page_name .= '.html';
        }
        $this->assign('full_page', 1);
        $this->assign('title', $this->title);
        $this->smarty->display($page_name);
    }
    /**
     * 直接抓取某页面数据
     * @param string $page_name 页面
     * @param string $cache_id 缓存ID
     */
    public function fetch($page_name, $cache_id = null) {
        if(strpos($page_name, '.html') === false) {
            $page_name .= '.html';
        }
        return $this->smarty->fetch($page_name, $cache_id);
    }
    /**
     * 跳转
     * @param string $class 文件名即类名，若actionContrlloer 可为aciton
     * @param string $method 方法名称
     */
    protected function redirect($class, $method) {
        $url = 'index.php?c=' . $class . '&m=' . $method;
        header("Location:$url");
    }
    /**
     * 打印信息
     * @param string $info 打印的信息
     * @param string $back_url 可选 跳转目标URL，默认上一页面,如c=user&m=view，　也可以全url
     * @param string $auto_redirect 可选，默认true 是否自动跳转     
     * @param int $second 可选 默认3秒跳转
     */
    public function show_msg($info, $back_url = '', $auto_redirect = true, $second = 3) {
        $message = array(
            'info' => $info,            
            'second' => $second,
        );
        if($auto_redirect) {
            $message['auto_redirect'] = true;
        }
        if($back_url) {
            if(stripos($back_url, 'c') !== false && stripos($back_url, 'm') !== false) {
                $back_url = 'index.php?' . $back_url;
            }
            $message['back_url'] = $back_url;                  
        } else {
            $message['back_url'] = $_SERVER['HTTP_REFERER'];
        }
        if(isset($_REQUEST['ajax'])) {
            $ret = array('status' => 100, 'msg' => $info);
            exit(json_encode($ret));
        }
        $this->assign('message', $message);
        $this->display('msg');exit;
    }
    public static function fatalError($e) {
        $this->assign('e', $e);
        $this->display('fatalError');
    }

    /**
     * 产生token
     */
    protected function create_token() {
        $token = ApiBase::load()->get_unique_id(32, 'token');
        $_SESSION['token'] = $token;
        $this->assign('token', $token);
    }
    /**
     * 验证TOKEN
     */
    protected function check_token() {        
        if(isset($_SESSION['token']) && isset($_REQUEST['token'])) {
            $token = $_REQUEST['token'];
            $ses_token = $_SESSION['token'];
            if($ses_token != $token) {
                $this->show_msg('非法提交');
            } else {
                unset($_SESSION['token']);
            }
        } else {
            $this->show_msg('异常提交,刷新后', 'c=login&m=index');
        }
    }
    
}
/**
 * 前台controller
 * 需要Session继承的Controller
 */
class Controller extends BaseController
{
    /**用户USER_ID*/
    protected $user_id = 0;    
    public function __construct() {
        parent::__construct();
        $this->user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
    }
    /**
     * 写日志
     * @param string $content 内容
     */
    protected function admin_log($content){
        AdminLogModel::load()->add($content, $this->log_type, $this->user_id);
    }
    /**
     * 设置返回json结构数据
     * @param int $status 状态码
     * @param string $msg 信息
     * @return type
     */
    protected function setReturn($status, $msg) {
        $this->ret['status'] = $status;
        $this->ret['msg'] = $msg;
        return json_encode($this->ret);
    }
    
}
/**
 * 需要Session继承的Controller
 */
class AppController extends Controller
{
    /**model对象*/
    protected $modelObj = null;
    
    public function __construct() {
        parent::__construct();
        $this->page_number = $GLOBALS['_CFG']['page_number'];
        if(in_array(APP_DEBUG, array(0, 1))) {
            $this->checkLogin();        
            $this->checkAuth();
        }
    }
    
    /**
     * 检查是否登陆过
     */
    public function checkLogin(){           
        if(!isset($_SESSION['user_id'])) {
            $this->redirect('manager', 'index');
        }
    }
    /**
     * 检查权限
     */
    private function checkAuth(){
        if(!$this->checkIsAdmin()) {            
            if(isset($_GET['c']) && isset($_GET['m'])) {
                $class = trim($_GET['c']);
                $method = trim($_GET['m']);
                if($class && $method) {
                    $auth_code = $class . ':' . $method;
                    $user_allot_arr = AdminUserModel::load()->get_allot_array($this->user_id,false);
                    if($user_allot_arr) {
                        $allot_str = '';
                        foreach ($user_allot_arr as $allot) {
                            $allot_str .= "'{$allot}',";
                        }
                        $allot_str = trim($allot_str, ',');
                        $rel_action_code_arr = AdminActionModel::load()->get_rel_action_code($allot_str);                        
                        if($rel_action_code_arr) {
                            //合并权限　
                            $user_allot_arr = array_merge($user_allot_arr, $rel_action_code_arr);
                        }
                    }     
                    if(empty($user_allot_arr) || !in_array($auth_code, $user_allot_arr)) {
                        $allot_err = '抱歉，您没有此权限，请向管理员申请权限代码「'.$auth_code.'」';
                        if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] == 1) {
                            echo $this->setReturn(100, $allot_err);exit;
                        } else {
                            $this->show_msg($allot_err, '', false);
                        }
                        
                    }
                }
            } else {
                $this->show_msg('超出权限，非法操作');
            }
        }
    }
    /**
     * 檢查 是否是管理員 後期優化
     * @return boolean 
     */
    protected function checkIsAdmin() {
        $is_admin = AdminUserModel::load()->get_is_admin($this->user_id);
        return intval($is_admin) == 0 ? false : true;
    }
    
    /**
     * 读取COOKIE
     */
    protected function get_cookie() {
        $cookie = getCookies($this->cookie_key);
        if($cookie) {
            $cookie_arr = json_decode(stripslashes($cookie), true);
            $this->assign('cookie', $cookie_arr);
        }
    }
    /**
     * 设置COOKIE
     * @param array $data 数据
     */
    protected function set_cookie($data) {        
        $time = time() + 600;
        setCookies($this->cookie_key, json_encode($data));        
    }

    /**
     * 设置最后一次查询条件
     * @param type $lastfilter
     */
    protected function set_filter($lastfilter){
        $filterfile = $_SERVER['REQUEST_URI'];
        setCookies('filter[file]', sprintf('%X', crc32($filterfile)), time() + 600);
        setCookies('filter[filter]', serialize($lastfilter),  time() + 600);
    }
    /**
     * 获取最近一次的查询条件
     * @param type $param_str
     * @return boolean
     */
    protected function get_filter(){
        $filterfile = $_SERVER['REQUEST_URI'];  
        $xfile = sprintf('%X', crc32($filterfile));
        if(getCookies('filter[file]') == $xfile)
        {
            return unserialize(getCookies('filter[filter]'));
        } 
        return false;
    }        
    /**
     * 编辑更新
     * @param string $fields 更新的字段名称
     */
    public function edit_fields() {
        if(empty($this->modelObj)){
            mylogger($this->modelObj, 'modelObj为空');
        }
        $id = intval($_POST['id']);
        if($id > 0) {
            $val = empty($_POST['val']) ? '' : urldecode($_POST['val']);
            $fields = trim($_POST['fields']);
            $data = array(
                $fields => $val,
            );
            $keyfields = $this->modelObj->keyFields;
            $where = array(
                $keyfields => $id,
            );
            $bool = $this->modelObj->update($data, $where);
            if($bool) {
                $this->ret['status'] = 0;
                $this->ret['msg'] = $val;
            }
        }
        exit(json_encode($this->ret));
    }
    /**
     * 删除
     */
    public function remove() {
        if(empty($this->modelObj)){
            mylogger($this->modelObj, 'modelObj为空');
        }
        $id = intval($_POST['id']);
        if($id > 0){
            $keyfields = $this->modelObj->keyFields;
            $where = array(
                $keyfields => $id,
            );
            $bool = $this->modelObj->delete($where);  
            if($bool) {
                $this->ret['status'] = 0;            
            }
        }
        exit(json_encode($this->ret));
    }
    /**
     * 改变是否停用
     */
    public function toggle() {
        if(empty($this->modelObj)){
            mylogger($this->modelObj, 'modelObj为空');
        }
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        if($id > 0) {            
            $where = array(
                $this->modelObj->keyFields => $id,
            );
            $info = $this->modelObj->getRow(null, $where);
            if($info) {
                $val = $_POST['val'];
                $fields = trim($_POST['fields']);
                $data = array(
                    $fields => $val,
                );                
                $bool = $this->modelObj->update($data, $where);
                if($bool) {
                    $this->ret['status'] = 0;                
                }
            }
        }
        echo json_encode($this->ret);
    }
    
}
/**
 * 无需session继承的controller
 */
class NotController extends BaseController
{
    public function __construct() {
        parent::__construct();
    }    
    /**
     * 日志记录
     * @param string $content 内容
     */
    protected function admin_log($content) {
        AdminLogModel::load()->add($content, '用户登陆');
    }
}
